package com.sofwin.system.controller;

import com.github.pagehelper.PageInfo;
import com.sofwin.common.ResponseEntry;
import com.sofwin.pojo.SysRole;
import com.sofwin.system.service.RoleService;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @packageName: com.sofwin.system.controller
 * @user: andyliu
 * @date: 2021/12/16 15:46
 * @email 115176513@qq.com
 * @description: TODO
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/index")
    public String toRoles(){
        return "role/index";
    }
    @PostMapping
    @ResponseBody
    public ResponseEntry data(SysRole role,
                            @RequestParam(required =true,defaultValue = "1") Integer pageNumber,
                              @RequestParam(required = true,defaultValue = "15") Integer pageSize){
        PageInfo<SysRole> roles = roleService.selectByPage(role,pageNumber,pageSize);
        return ResponseEntry.success(roles);
    }
    @GetMapping("toEdit")
    public String toEdit(Integer id, Model model){
        if(id!=null){
           SysRole role =  roleService.selectById(id);
           model.addAttribute("role",role);
        }
        return "role/edit";
    }
    @PostMapping("save")
    @ResponseBody
    public ResponseEntry save(SysRole role){
        boolean status = roleService.saveOrUpdate(role);
        if(status)return ResponseEntry.success("保存成功");
        return ResponseEntry.error("保存失败");
    }
    @DeleteMapping("dele/{id}")
    @ResponseBody
    public ResponseEntry deleteById(@PathVariable Integer id){
        boolean status = roleService.deleteById(id);
        if(status)return ResponseEntry.success("删除成功");
        return ResponseEntry.error("删除失败");
    }
    @GetMapping("deletes")
    @ResponseBody
    public ResponseEntry deletes(@RequestParam("ids[]") Integer[] ids){
        boolean status = roleService.deleteByIds(ids);
        if(status)return ResponseEntry.success("删除成功");
        return ResponseEntry.error("删除失败");
    }

    @GetMapping("toPermission")
    public String toRolePermission(Integer roleId,Model model){
        model.addAttribute("roleId",roleId);
        return "role/permission";
    }
    @GetMapping("savePermission")
    @ResponseBody
    public ResponseEntry savePermission(Integer roleId,@RequestParam("ids[]") Integer[] ids){
        boolean status = roleService.savePermission(roleId,ids);
        if(status)return ResponseEntry.success("保存成功");
        return ResponseEntry.error("保存失败");
    }

}
